<?php

namespace xcxApi\modules\product\controllers;

use common\components\fast_api\Controller;
use common\models\db\Files;
use xcxApi\models\db\Products;
use yii\data\ActiveDataProvider;

class DefaultController extends Controller
{
    /**
     * 列表
     * @param int $page 页码
     * @param string $searchStr 搜索
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function actionList($page = 1, $pageSize = 10, $selCate = -10, $searchStr = null)
    {
        $query = Products::find();
        $query->andFilterWhere(['status' => Products::STATUS_ACTIVE]);
        if ($searchStr) {
            $query->andFilterWhere(['like', 'name', $searchStr]);
        }
        if ($selCate != -10) {
            $query->andFilterWhere(['cate_root' => $selCate]);
        }
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'page' => $page - 1,
                'pageSize' => $pageSize,
            ],
            'sort' => ['defaultOrder' => [
                'product_sort' => SORT_ASC,
                'id' => SORT_DESC,
            ]],
        ]);
        $items = [];
        foreach ($dataProvider->models as $k => $v) {
            /** @var Products $v */
            $m = $v->toArray();
            $m['_created_at'] = date("Y-m-d H:i", $v->created_at);
            $m['_status'] = $v::getStatusDesc()[$v->status];
            $m['cover'] = Files::thumbImageUrl($v->cover);
            if (!$m['specs']) $m['specs'] = '未设置';
            if (!$m['hnumbering']) $m['hnumbering'] = '未设置';
            $items[] = $m;
        }
        $data = [
            'items' => $items,
            'count' => $dataProvider->count,
            '_meta' => [
                'totalCount' => $dataProvider->totalCount,
                'pageCount' => $dataProvider->pagination->pageCount,
                'currentPage' => $dataProvider->pagination->page + 1,
                'perPage' => $dataProvider->pagination->pageSize,
            ],
        ];
        return $this->apiSuccess($data, '获取商品列表成功');
    }

    /**
     * 详情
     * @desc post
     * @param int $id 商品id
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function actionDetail($id)
    {
//        $model = Products::findOne($id);
        $model = Products::find()
            ->where(['id' => $id])
            ->with('type4Material')
            ->one();
        if (!$model) {
            return $this->apiError('商品不存在');
        }
        $material = $model->type4Material ? $model->type4Material->content : '';
        return $this->apiSuccess([
            'product' => $model,
            'material' => $material,
        ], '获取商品详情成功');
    }
}
